const multer = require('multer')
const path = require('path')
const sd = require('silly-datetime')
const mkdirp = require('mkdirp')
let tools = {
  multer() {
    const storage = multer.diskStorage({
      destination: async (req, file, cb) => {
        let data = sd.format(new Date(), 'YYYYMMDD')
        let dir = path.join('/static/uploads', data)
        await mkdirp(dir)
        cb(null, dir)
      },
      filename: (req, file, cb) => {
        let extname = path.extnmae(file.originalname)
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9)
        cb(null, file.fieldname + '-' + uniqueSuffix + '.' + extname)
      },
    })

    const upload = multer({ storage: storage })

    return upload
  },
}

module.exports = tools
